﻿using DiLe.Mes.Application.Cloud.Dashboard;
using DiLe.Mes.Application.Cloud.Statistics;
using DiLe.Mes.Application.Common;
using DiLe.Mes.Application.Common.Equipment;
using DiLe.Mes.Application.Handler;
using DiLe.Mes.Cloud.Controllers.Dashboard.Dto;
using DiLe.Mes.Model.Cloud.Dashboard.Equipment;
using DiLe.Mes.Model.Cloud.Dashboard.Statistics;
using DiLe.Mes.Model.Common.Equipment.Entity.Maintenance;
using DiLe.Mes.Model.Common.Equipment.Entity.Manage;
using DiLe.Mes.Model.Common.Organization.Entity;
using DiLe.Mes.Service.Dto;
using MapleLeaf.Core.Excel;
using Microsoft.AspNetCore.Authorization;

namespace DiLe.Mes.Cloud.Controllers.Dashboard {
    /// <summary>
    /// 设备Dashboard
    /// </summary>
    [AllowAnonymous]
    [ApiExplorerSettings(GroupName = ApiCloudGroupConst.Dashboard)]
    public class EquipmentDashboardController : ApiBaseController {

        private readonly EquipmentDashboardClient _client;
        private readonly EquipmentManageClient _equipmentclient;
        private readonly EquipmentExjosnHandler _handler;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly WorkOrderClient _workOrder;
        private readonly EquipmentMaintenanceClient _maintenanceClient;
        private readonly EquipmentRepairClient _equipmentRepair;
        private readonly OrganizationClient _organizationClient;
        private readonly StatisticsClient _statisticsClient;

        /// <summary>
        /// 
        /// </summary>
        public EquipmentDashboardController(EquipmentDashboardClient equipmentDashboard,
                                            EquipmentManageClient equipmentManage,
                                            EquipmentExjosnHandler handler,
                                            IWebHostEnvironment webHostEnvironment,
                                            WorkOrderClient workOrderClient,
                                            EquipmentMaintenanceClient equipmentMaintenanceClient,
                                            EquipmentRepairClient equipmentRepairClient,
                                            OrganizationClient organizationClient,
                                            StatisticsClient statisticsClient) {
            _client = equipmentDashboard;
            _handler = handler;
            _equipmentclient = equipmentManage;
            _webHostEnvironment = webHostEnvironment;
            _workOrder = workOrderClient;
            _maintenanceClient = equipmentMaintenanceClient;
            _equipmentRepair = equipmentRepairClient;
            _organizationClient = organizationClient;
            _statisticsClient = statisticsClient;
        }

        /// <summary>
        /// 获取设备Dashboard列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<OrganizationEntity>>> GetFactoryList() {
            var list = await _organizationClient.GetOrganizationListAsync(p => p.Type == "Factory");
            return Success(list);
        }

        /// <summary>
        /// 获取设备Dashboard列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<EquipmentDashboardDto>> GetEquipmentDashboard() {
            long orgid = AppHelper.QueryOrgId;
            var dto = new EquipmentDashboardDto {
                PointInfoList = await GetPointInfoListAsync(orgid),
                TrimlPointInfoList = await GetTrimPointInfoListAsync(orgid),
                AOIPointInfoList = await GetAOIPointInfoListAsync(orgid),
                PMPointInfoList = await GetCloudFMPointInfos(orgid),
                EMPointInfoList = await GetCloudEMPointInfos(orgid),
                OtherPointInfoList = await Get1311PointInfoListAsync(orgid)
            };

            return Success(dto);
        }
        #region 导出
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportFile() {
            long orgid = AppHelper.QueryOrgId;


            var PointInfoList = await GetPointInfoListAsync(orgid);
            var TrimlPointInfoList = await GetTrimPointInfoListAsync(orgid);
            var AOIPointInfoList = await GetAOIPointInfoListAsync(orgid);
            var PMPointInfoList = await GetCloudFMPointInfos(orgid);
            var EMPointInfoList = await GetCloudEMPointInfos(orgid);
            var OtherPointInfoList = await Get1311PointInfoListAsync(orgid);


            var forming = new ExportExcelModel() {
                Title = "当日成型设备数据"
            };
            var formingdic = CommonHelper.GetFormingHeaderRows();
            forming.DtSource.AddRange(PointInfoList);
            forming.Columns = new ExportColumnCollective {
                ExportColumnList = formingdic,
                HeaderExportColumnList = [formingdic]
            };

            var other = new ExportExcelModel() {
                Title = "当日1311设备数据"
            };
            var otherdic = CommonHelper.GetOtherHeaderRows();
            other.DtSource.AddRange(OtherPointInfoList);
            other.Columns = new ExportColumnCollective {
                ExportColumnList = otherdic,
                HeaderExportColumnList = [otherdic]
            };



            var trim = new ExportExcelModel() {
                Title = "当日切边机数据"
            };
            var trimdic = CommonHelper.GetTrimHeaderRows();
            trim.DtSource.AddRange(TrimlPointInfoList);
            trim.Columns = new ExportColumnCollective {
                ExportColumnList = trimdic,
                HeaderExportColumnList = [trimdic]
            };

            var aoi = new ExportExcelModel() {
                Title = "当日AOI设备数据"
            };
            var aoidic = CommonHelper.GetAOIHeaderRows();
            aoi.DtSource.AddRange(AOIPointInfoList);
            aoi.Columns = new ExportColumnCollective {
                ExportColumnList = aoidic,
                HeaderExportColumnList = [aoidic]
            };

            var em = new ExportExcelModel() {
                Title = "当日ESG数据-电能表"
            };
            var emdic = CommonHelper.GetEMHeaderRows();
            em.DtSource.AddRange(AOIPointInfoList);
            em.Columns = new ExportColumnCollective {
                ExportColumnList = emdic,
                HeaderExportColumnList = [emdic]
            };

            var fm = new ExportExcelModel() {
                Title = "当日ESG数据-流量表"
            };
            var fmdic = CommonHelper.GetFMHeaderRows();
            fm.DtSource.AddRange(AOIPointInfoList);
            fm.Columns = new ExportColumnCollective {
                ExportColumnList = fmdic,
                HeaderExportColumnList = [fmdic]
            };
            var list = new List<ExportExcelModel> { forming, other, aoi, trim, };
            var excelFileName = $"设备Dashboard({DateTime.Now:yyyyMMdd}).xlsx";

            var bytes = Export2Excel.Export(list);

            // 设置响应头信息
            HttpContext.Response.Headers.AccessControlExposeHeaders = "Content-Disposition";

            return File(bytes, "application/octet-stream", excelFileName);
        }


        #endregion
        /// <summary>
        /// 成型机
        /// </summary>
        /// <returns></returns>
        private async Task<List<CloudPointInfoModel>> GetPointInfoListAsync(long orgid) {
            var list = new List<CloudPointInfoModel>();
            var wxp = Expressionable.Create<CloudPointInfoEntity>();
            wxp.And(p => p.DataUploadDate == DateTime.Now.Date);
            wxp.And(p => p.FactoryId == orgid);
            var datas = await _client.GetPointInfoListAsync(wxp.ToExpression());

            var dataMaps = datas.GroupBy(x => x.DeviceNo).Select(p => (p.Key, p.OrderBy(p => p.CreateTime).LastOrDefault())).ToList();
            if (dataMaps.None()) {
                return list;
            }
            var codeList = datas.Where(p => !p.DeviceNo.IsNullOrEmpty()).Select(x => x.DeviceNo).Distinct().ToList();
            var temps = await _equipmentclient.GetEquipmentRegisterListAsync(p => codeList.Contains(p.EquipmentSign));
            var registerInfolist = await _handler.GetEquipmentRegisterExjosn(temps);

            foreach (var item in dataMaps) {
                if (item.Item2 == null || item.Item2.DeviceNo.IsNullOrEmpty()) {
                    continue;
                }
                var model = item.Item2.Adapt<CloudPointInfoModel>();
                var info = registerInfolist?.FirstOrDefault(p => p.Model.EquipmentSign == model.DeviceNo);
                if (info == null) {
                    continue;
                }
                model.EquipmentName = info?.Equipment.Name ?? "";
                model.EquipmentCode = info?.Equipment.Code ?? "";
                model.Specification = info?.Equipment.Specification ?? "";
                model.EquipmentPosition = info?.Equipment.ExtJson["PositionName"]?.ToString() ?? "";
                model.FactoryName = info?.Equipment.ExtJson["FactoryName"]?.ToString() ?? "";
                model.EquipmentType = info?.Equipment.ExtJson["TypeName"]?.ToString() ?? "";
                //左侧热压下模温度
                if (!model.LeftUpperTemp.IsNullOrEmpty()) {
                    var arr = model.LeftUpperTemp.Split(",");
                    if (arr.Length > 0) {
                        model.LeftUpperTemp1 = arr[0];
                    }
                    if (arr.Length > 1) {
                        model.LeftUpperTemp2 = arr[1];
                    }
                    if (arr.Length > 2) {
                        model.LeftUpperTemp3 = arr[2];
                    }
                    if (arr.Length > 3) {
                        model.LeftUpperTemp4 = arr[3];
                    }
                }
                //左侧热压下模温度
                if (!model.LeftDownTemp.IsNullOrEmpty()) {
                    var arr = model.LeftDownTemp.Split(",");
                    if (arr.Length > 0) {
                        model.LeftDownTemp1 = arr[0];
                    }
                    if (arr.Length > 1) {
                        model.LeftDownTemp2 = arr[1];
                    }
                    if (arr.Length > 2) {
                        model.LeftDownTemp3 = arr[2];
                    }
                    if (arr.Length > 3) {
                        model.LeftDownTemp4 = arr[3];
                    }
                }
                //右侧热压上模温度
                if (!model.RightUpperTemp.IsNullOrEmpty()) {
                    var arr = model.RightUpperTemp.Split(",");
                    if (arr.Length > 0) {
                        model.RightUpperTemp1 = arr[0];
                    }
                    if (arr.Length > 1) {
                        model.RightUpperTemp2 = arr[1];
                    }
                    if (arr.Length > 2) {
                        model.RightUpperTemp3 = arr[2];
                    }
                    if (arr.Length > 3) {
                        model.RightUpperTemp4 = arr[3];
                    }
                }
                //右侧热压下模温度
                if (!model.RightDownTemp.IsNullOrEmpty()) {
                    var arr = model.RightDownTemp.Split(",");
                    if (arr.Length > 0) {
                        model.RightDownTemp1 = arr[0];
                    }
                    if (arr.Length > 1) {
                        model.RightDownTemp2 = arr[1];
                    }
                    if (arr.Length > 2) {
                        model.RightDownTemp3 = arr[2];
                    }
                    if (arr.Length > 3) {
                        model.RightDownTemp4 = arr[3];
                    }
                }
                model.EquipmentStatus = Calculate(model.AcquisitionTime!.Value) >= 15 ? "离线" : "在线";
                list.Add(model!);
            }
            //使用自定义比较器进行数字排序
            List<CloudPointInfoModel> sortedList = list.OrderBy(o => o.EquipmentName).OrderBy(p => p.OrderNum).ToList();
            return sortedList;
        }
        /// <summary>
        /// 成型机-1311
        /// </summary>
        /// <returns></returns>
        private async Task<List<CloudOtherPointInfoModel>> Get1311PointInfoListAsync(long orgid) {
            var list = new List<CloudOtherPointInfoModel>();

            var wxp = Expressionable.Create<CloudOtherPointInfoEntity>();
            wxp.And(p => p.DataUploadDate == DateTime.Now.Date);
            wxp.And(p => p.FactoryId == orgid);

            var datas = await _client.Get1311PointInfoListAsync(wxp.ToExpression());
            var dataMaps = datas.GroupBy(x => x.DeviceNo).Select(p => (p.Key, p.OrderBy(p => p.CreateTime).LastOrDefault())).ToList();
            if (dataMaps.None()) {
                return list;
            }
            var codeList = datas.Where(p => !p.DeviceNo.IsNullOrEmpty()).Select(x => x.DeviceNo).Distinct().ToList();
            var temps = await _equipmentclient.GetEquipmentRegisterListAsync(p => codeList.Contains(p.EquipmentSign));
            var registerInfolist = await _handler.GetEquipmentRegisterExjosn(temps);
            registerInfolist = registerInfolist.Where(p => p.Equipment.FactoryId == orgid).ToList();
            foreach (var item in dataMaps) {
                if (item.Item2 == null || item.Item2.DeviceNo.IsNullOrEmpty()) {
                    continue;
                }
                var model = item.Item2.Adapt<CloudOtherPointInfoModel>();
                var info = registerInfolist?.FirstOrDefault(p => p.Model.EquipmentSign == model.DeviceNo);
                if (info == null) {
                    continue;
                }
                model.EquipmentName = info?.Equipment.Name ?? "";
                model.EquipmentCode = info?.Equipment.Code ?? "";
                model.Specification = info?.Equipment.Specification ?? "";
                model.EquipmentPosition = info?.Equipment.ExtJson["PositionName"]?.ToString() ?? "";
                model.FactoryName = info?.Equipment.ExtJson["FactoryName"]?.ToString() ?? "";
                model.EquipmentType = info?.Equipment.ExtJson["TypeName"]?.ToString() ?? "";


                //左侧热压下模温度
                if (!model.LeftUpperTemp.IsNullOrEmpty()) {
                    var arr = model.LeftUpperTemp.Split(",");
                    if (arr.Length > 0) {
                        model.LeftUpperTemp1 = arr[0];
                    }
                    if (arr.Length > 1) {
                        model.LeftUpperTemp2 = arr[1];
                    }
                    if (arr.Length > 2) {
                        model.LeftUpperTemp3 = arr[2];
                    }
                    if (arr.Length > 3) {
                        model.LeftUpperTemp4 = arr[3];
                    }
                }
                //左侧热压下模温度
                if (!model.LeftDownTemp.IsNullOrEmpty()) {
                    var arr = model.LeftDownTemp.Split(",");
                    if (arr.Length > 0) {
                        model.LeftDownTemp1 = arr[0];
                    }
                    if (arr.Length > 1) {
                        model.LeftDownTemp2 = arr[1];
                    }
                    if (arr.Length > 2) {
                        model.LeftDownTemp3 = arr[2];
                    }
                    if (arr.Length > 3) {
                        model.LeftDownTemp4 = arr[3];
                    }
                }
                //右侧热压上模温度
                if (!model.RightUpperTemp.IsNullOrEmpty()) {
                    var arr = model.RightUpperTemp.Split(",");
                    if (arr.Length > 0) {
                        model.RightUpperTemp1 = arr[0];
                    }
                    if (arr.Length > 1) {
                        model.RightUpperTemp2 = arr[1];
                    }
                    if (arr.Length > 2) {
                        model.RightUpperTemp3 = arr[2];
                    }
                    if (arr.Length > 3) {
                        model.RightUpperTemp4 = arr[3];
                    }
                }
                //右侧热压下模温度
                if (!model.RightDownTemp.IsNullOrEmpty()) {
                    var arr = model.RightDownTemp.Split(",");
                    if (arr.Length > 0) {
                        model.RightDownTemp1 = arr[0];
                    }
                    if (arr.Length > 1) {
                        model.RightDownTemp2 = arr[1];
                    }
                    if (arr.Length > 2) {
                        model.RightDownTemp3 = arr[2];
                    }
                    if (arr.Length > 3) {
                        model.RightDownTemp4 = arr[3];
                    }
                }
                model.EquipmentStatus = Calculate(model.AcquisitionTime!.Value) >= 15 ? "离线" : "在线";
                list.Add(model!);
            }
            //使用自定义比较器进行数字排序
            List<CloudOtherPointInfoModel> sortedList = list.OrderBy(o => o.OrderNum).ToList();
            return sortedList;
        }
        /// <summary>
        /// 切边机
        /// </summary>
        /// <returns></returns>
        private async Task<List<CloudTrimPointInfoModel>> GetTrimPointInfoListAsync(long orgid) {
            var list = new List<CloudTrimPointInfoModel>();

            var wxp = Expressionable.Create<CloudTrimPointInfoEntity>();
            wxp.And(p => p.DataUploadDate == DateTime.Now.Date);
            wxp.And(p => p.FactoryId == orgid);

            var datas = await _client.GetTrimlPointInfoListAsync(wxp.ToExpression());
            var dataMaps = datas.GroupBy(x => x.DeviceNo).Select(p => (p.Key, p.OrderBy(p => p.CreateTime).LastOrDefault())).ToList();
            if (dataMaps.None()) {
                return list;
            }
            var codeList = datas.Where(p => !p.DeviceNo.IsNullOrEmpty()).Select(x => x.DeviceNo).Distinct().ToList();
            var temps = await _equipmentclient.GetEquipmentRegisterListAsync(p => codeList.Contains(p.EquipmentSign));
            var registerInfolist = await _handler.GetEquipmentRegisterExjosn(temps);


            foreach (var item in dataMaps) {
                if (item.Item2 == null || item.Item2.DeviceNo.IsNullOrEmpty()) {
                    continue;
                }
                var model = item.Item2.Adapt<CloudTrimPointInfoModel>();
                var info = registerInfolist?.FirstOrDefault(p => p.Model.EquipmentSign == model.DeviceNo);
                if (info == null) {
                    continue;
                }
                model.EquipmentName = info?.Equipment.Name ?? "";
                model.EquipmentCode = info?.Equipment.Code ?? "";
                model.Specification = info?.Equipment.Specification ?? "";
                model.EquipmentPosition = info?.Equipment.ExtJson["PositionName"]?.ToString() ?? "";
                model.FactoryName = info?.Equipment.ExtJson["FactoryName"]?.ToString() ?? "";
                model.EquipmentType = info?.Equipment.ExtJson["TypeName"]?.ToString() ?? "";
                model.EquipmentStatus = Calculate(model.AcquisitionTime!.Value) >= 15 ? "离线" : "在线";

                list.Add(model!);
            }
            var sortedList = list.OrderBy(o => o.EquipmentCode).ToList();
            return sortedList;
        }
        /// <summary>
        /// AOI
        /// </summary>
        /// <returns></returns>
        private async Task<List<CloudAOIPointInfoModel>> GetAOIPointInfoListAsync(long orgid) {
            var list = new List<CloudAOIPointInfoModel>();
            var whereExp = Expressionable.Create<CloudAOIPointInfoEntity>();
            whereExp.And(p => p.DataUploadDate == DateTime.Now.Date);
            whereExp.And(p => p.FactoryId == orgid);

            var datas = await _client.GetAOIPointInfoListAsync(whereExp.ToExpression());
            var dataMaps = datas.GroupBy(x => x.DeviceNo).Select(p => (p.Key, p.OrderBy(p => p.CreateTime).LastOrDefault())).ToList();
            if (dataMaps.None()) {
                return list;
            }
            var codeList = datas.Where(p => !p.DeviceNo.IsNullOrEmpty()).Select(x => x.DeviceNo).Distinct().ToList();
            var temps = await _equipmentclient.GetEquipmentRegisterListAsync(p => codeList.Contains(p.EquipmentSign));
            var registerInfolist = await _handler.GetEquipmentRegisterExjosn(temps);

            foreach (var item in dataMaps) {
                if (item.Item2 == null || item.Item2.DeviceNo.IsNullOrEmpty()) {
                    continue;
                }
                var model = item.Item2.Adapt<CloudAOIPointInfoModel>();
                var info = registerInfolist?.FirstOrDefault(p => p.Model.EquipmentSign == model.DeviceNo);
                if (info == null) {
                    continue;
                }
                model.EquipmentName = info?.Equipment.Name ?? "";
                model.EquipmentCode = info?.Equipment.Code ?? "";
                model.Specification = info?.Equipment.Specification ?? "";
                model.EquipmentPosition = info?.Equipment.ExtJson["PositionName"]?.ToString() ?? "";
                model.FactoryName = info?.Equipment.ExtJson["FactoryName"]?.ToString() ?? "";
                model.EquipmentType = info?.Equipment.ExtJson["TypeName"]?.ToString() ?? "";
                model.EquipmentStatus = Calculate(model.AcquisitionTime!.Value) >= 15 ? "离线" : "在线";
                list.Add(model!);
            }
            var sortedList = list.OrderBy(o => o.EquipmentName).ToList();
            return sortedList;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private async Task<List<CloudEMPointInfoModel>> GetCloudEMPointInfos(long orgid) {
            var list = new List<CloudEMPointInfoModel>();
            var whereExp = Expressionable.Create<CloudEMPointInfoEntity>();
            whereExp.And(p => p.DataUploadDate == DateTime.Now.Date);
            whereExp.And(p => p.FactoryId == orgid);

            var datas = await _client.GetEMPointInfoListAsync(whereExp.ToExpression());
            var dataMps = datas.GroupBy(p => p.DeviceNo).Select(x => (x.Key, x.OrderBy(p => p.CreateTime).LastOrDefault())).ToList();
            var NameArr1 = new List<string> { "AB线真空泵1#", "1311-01", "A线制浆1#", "AB线空压1#", "B线制浆2#", "AB线真空泵2#", "AB线空压2#", "B线制浆1#", "老配电房总电1#" };
            var NameArr2 = new List<string> { "CD线空压2#", "A线制浆2#", "老配电房总电2#", "AB线真空3#", "B线制浆3#" };
            var NameArr3 = new List<string> { "C线制浆1#", "三合一真空", "CD线真空1#", "CD线真空2#", "CD线真空3#", "新配电室总电1#", "新配电室总电2#", "圣代杯空压机", "三合一空压机", "D线制浆5#", "D线制浆4#", "D线制浆3#", "D线制浆2#", "D线制浆1#", "C线制浆5#", "C线制浆4#", "C线制浆3#", "C线制浆2#" };

            int ctIndex = 0;
            int id = 0;
            foreach (var item in dataMps) {
                int index = 0;
                List<string> NameArr = new();
                int orderNum = 0;
                if (item.Key?.ToLower() == "电能表-1") {
                    NameArr = NameArr1;
                    ctIndex = 8;
                    orderNum = 1;
                } else if (item.Key?.ToLower() == "电能表-2") {
                    NameArr = NameArr2;
                    ctIndex = 4;
                    orderNum = 40;
                } else if (item.Key?.ToLower() == "电能表-6") {
                    NameArr = NameArr3;
                    ctIndex = 17;
                    orderNum = 60;
                }
                var data = item.Item2;
                var valueArr = data!.EcTotal.Split(",");
                foreach (var value in valueArr) {
                    if (index > ctIndex) {
                        continue;
                    }
                    var m = new CloudEMPointInfoModel {
                        Id = ++id,
                        EcTotal = value,
                        DeviceBrand = data.DeviceBrand,
                        DeviceNo = NameArr[index],
                        OrderNum = ++orderNum,
                        AcquisitionTime = data.AcquisitionTime,
                        EquipmentStatus = Calculate(data.AcquisitionTime!.Value) >= 15 ? "离线" : "在线"
                    };
                    list.Add(m);
                    index++;
                }
            }
            var sortedList = list.OrderBy(o => o.DeviceNo).OrderBy(x => x.OrderNum).ToList();
            return sortedList;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns> 
        private async Task<List<CloudFMPointInfoModel>> GetCloudFMPointInfos(long orgid) {
            var list = new List<CloudFMPointInfoModel>();
            var whereExp = Expressionable.Create<CloudFMPointInfoEntity>();
            whereExp.And(p => p.DataUploadDate == DateTime.Now.Date);
            whereExp.And(p => p.FactoryId == orgid);
            var datas = await _client.GetFMPointInfoListAsync(whereExp.ToExpression());
            var dataMps = datas.GroupBy(p => p.DeviceNo).Select(x => (x.Key, x.OrderBy(p => p.CreateTime).LastOrDefault())).ToList();
            var NameArr1 = new List<(int num, string name)> { (2, "AB线打浆供水-流量表2"), (3, "CD线打浆供水-流量表3"), (4, "AB线回收-流量表4"), (5, "AB线回收-流量表5") };
            var NameArr2 = new List<(int num, string name)> { (1, "总供水-流量表1") };
            var NameArr3 = new List<(int num, string name)> { (6, "CD线回收-流量表6"), (7, "CD线回收-流量表7") };
            int ctIndex = 0;
            int id = 0;
            foreach (var item in dataMps) {
                int index = 0;
                List<(int num, string name)> NameArr = new();
                if (item.Key?.ToLower() == "流量计-3") {
                    ctIndex = 3;
                    NameArr = NameArr1;
                } else if (item.Key?.ToLower() == "流量计-5") {
                    ctIndex = 1;
                    NameArr = NameArr3;
                } else if (item.Key?.ToLower() == "流量计-2") {
                    ctIndex = 0;
                    NameArr = NameArr2;
                }
                if (NameArr.None()) {
                    continue;
                }
                var data = item.Item2;
                var valueArr = data!.FlowTotal.Split(",");
                foreach (var value in valueArr) {
                    if (index > ctIndex) {
                        continue;
                    }
                    var m = new CloudFMPointInfoModel {
                        Id = ++id,
                        FlowTotal = value,
                        DeviceBrand = data.DeviceBrand,
                        DeviceNo = NameArr[index].name,
                        OrderNum = NameArr[index].num,
                        AcquisitionTime = data.AcquisitionTime,
                        EquipmentStatus = Calculate(data.AcquisitionTime!.Value) >= 15 ? "离线" : "在线"
                    };
                    list.Add(m);
                    index++;
                }
            }
            var sortedList = list.OrderBy(o => o.OrderNum).ToList();
            return sortedList;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="starttime"></param>
        /// <returns></returns>
        private static double Calculate(DateTime starttime) {
            TimeSpan span = DateTime.Now - starttime;
            return span.TotalMinutes;
        }



        /// <summary>
        /// 获取设备Dashboard列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<EquipmentDashboardModel>> GetEquipmentDashboard1() {
            var dto = new EquipmentDashboardModel();
            //设备
            var infomodels = await _equipmentclient.GetEquipmentInfoModelListAsync(AppHelper.QueryOrgId);
            //设备类型
            var typeList = await _equipmentclient.GetEquipmentTypeListAsync();

            var dic = GetEquipmentTypeDic(typeList);

            var plans = await _maintenanceClient.GetMaintenancePlanListAsync();
            await _handler.FillMaintenancePlanExjosn(plans);
            var signs = infomodels.ConvertAll(x => x.EquipmentCode);

            var list = _statisticsClient.GetAlarmInfoReportList(signs);

            dto.AlarmData = GetEquipmentAlarmModels(dic, infomodels, list);
            dto.EquipmentRepairList = await GetEquipmentRepairModelsAsync(dic, infomodels);
            dto.EquipmentPlanList = GetEquipmentPlanModels(dic, infomodels, plans);
            dto.EquipmentRecordList = await GetEquipmentRecordModelsAsync(dic, infomodels, plans);
            return Success(dto);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private List<EAStatistic> GetEquipmentAlarmModels(Dictionary<string, List<long>> dic, List<EquipmentInfoModel> datalist, List<AlarmInfoStatisticsEntity> alarms) {
            var list = new List<EAStatistic>();

            int index = 0;
            foreach (var item in dic) {
                var infos = datalist.Where(x => item.Value.Contains(x.EquipmentTypeId)).ToList();
                bool ck = item.Key == "冲切机";
                foreach (var info in infos) {
                    var alarmInfo = alarms.Where(x => x.EquipmentCode == info.EquipmentCode).ToList();
                    if (alarmInfo.None()) {
                        var m = info.Adapt<EAStatistic>();
                        m.Type = item.Key;
                        m.Id = ++index;
                        if (ck) {
                            m.EquipmentName = info.EquipmentSign;
                        }
                        list.Add(m);
                    } else {
                        foreach (var ms in alarmInfo) {
                            var m = info.Adapt<EAStatistic>();
                            m.Type = item.Key;
                            m.Id = ++index;
                            m.AlarmDate = DateTime.Parse(ms.AbnormalDate);
                            m.AbnormalInfo = ms.AbnormalInfo ?? "";
                            m.AbnormalLevel = ms.AbnormalLevel;
                            if (ck) {
                                m.EquipmentName = info.EquipmentSign;
                            }
                            list.Add(m);
                        }
                    }
                }
            }
            return list;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private async Task<List<EquipmentRepairModel>> GetEquipmentRepairModelsAsync(Dictionary<string, List<long>> dic, List<EquipmentInfoModel> datalist) {
            var list = new List<EquipmentRepairModel>();
            var repairs = await _equipmentRepair.GetRepairRecordListAsync();
            await _handler.FillRepairRecordExjosn(repairs);
            foreach (var item in dic) {
                var infos = datalist.Where(x => item.Value.Contains(x.EquipmentTypeId)).ToList();
                foreach (var info in infos) {
                    var irepairs = repairs.Where(x => x.EquipmentId == info.EquipmentId).ToList();
                    if (irepairs.None()) {
                        continue;
                    }
                    foreach (var irepair in irepairs) {
                        var m = info.Adapt<EquipmentRepairModel>();
                        m.Type = item.Key;
                        m.EquipmentCode = info.EquipmentCode;
                        m.EquipmentName = info.EquipmentName;
                        m.RepairCode = irepair.Code;
                        m.RepairEndDate = irepair.EndDate;
                        m.RepairSatrtDate = irepair.StartDate;
                        m.RepairManager = irepair.ExtJson["ManagerName"]?.ToString() ?? "";
                        list.Add(m);
                    }
                }
            }
            return list;
        }
        /// <summary>
        /// 保养计划
        /// </summary>
        /// <returns></returns>
        private static List<EPlanStatistic> GetEquipmentPlanModels(Dictionary<string, List<long>> dic,
                                                            List<EquipmentInfoModel> datalist,
                                                            List<MaintenancePlanEntity> plans) {
            var list = new List<EPlanStatistic>();

            foreach (var item in dic) {
                var infos = datalist.Where(x => item.Value.Contains(x.EquipmentTypeId)).ToList();
                foreach (var info in infos) {
                    var iplans = plans.Where(x => x.EquipmentId == info.EquipmentId).ToList();
                    if (iplans.None()) {
                        continue;
                    }
                    foreach (var ipn in iplans) {
                        var m = info.Adapt<EPlanStatistic>();
                        m.Type = item.Key;
                        m.StartDate = ipn.StartDate;
                        m.EndDate = ipn.EndDate;
                        m.PlanCode = ipn.Code;
                        m.PlanTypeName = ipn.PlanType;
                        m.MaintenanceManger = ipn.ExtJson["ManagerName"]?.ToString() ?? "";
                        list.Add(m);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 保养记录
        /// </summary>
        /// <returns></returns>
        private async Task<List<ERecordStatistic>> GetEquipmentRecordModelsAsync(Dictionary<string, List<long>> dic,
                                                                                 List<EquipmentInfoModel> datalist,
                                                                                 List<MaintenancePlanEntity> plans) {
            var list = new List<ERecordStatistic>();
            var records = await _maintenanceClient.GetMaintenanceRecordListAsync();

            foreach (var item in dic) {
                var infos = datalist.Where(x => item.Value.Contains(x.EquipmentTypeId)).ToList();
                foreach (var info in infos) {
                    var irecords = records.Where(x => x.EquipmentId == info.EquipmentId).ToList();
                    if (irecords.None()) {
                        continue;
                    }
                    foreach (var ird in irecords) {
                        var m = info.Adapt<ERecordStatistic>();
                        m.Type = item.Key;
                        var plan = plans.FirstOrDefault(x => x.Id == ird.MaintenancePlanId);
                        m.StartDate = plan?.StartDate;
                        m.EndDate = plan?.EndDate;
                        m.MaintenanceCode = plan?.Code ?? "";
                        m.MaintenanceType = plan?.PlanType ?? "";
                        m.MaintenanceManger = plan?.ExtJson["ManagerName"]?.ToString() ?? "";
                        list.Add(m);
                    }
                }
            }
            return list;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static Dictionary<string, List<long>> GetEquipmentTypeDic(List<EquipmentTypeEntity> typelist) {
            var dic = new Dictionary<string, List<long>>();
            var temps = typelist.Where(p => p.ParentId == 0).ToList();
            foreach (var item in temps) {
                var items = GetChildEquipmentTypeList(item.Id, typelist);
                if (items.None()) {
                    continue;
                }
                items.Add(item.Id);
                dic[item.Name] = items;
            }
            return dic;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static List<long> GetChildEquipmentTypeList(long parentId, List<EquipmentTypeEntity> typelist) {
            var list = new List<long>();
            var temps = typelist.Where(p => p.ParentId == parentId).ToList();
            foreach (var item in temps) {
                list.Add(item.Id);
                var items = GetChildEquipmentTypeList(item.Id, typelist);
                if (!items.None()) {
                    list.AddRange(items);
                }
            }
            return list;
        }
    }
}
